//  WXApiManager.m
#import "WXApiManager.h"

static int State = 0;
static char* Result = "";

//防止内存泄漏，崩溃，这里进行参数转换
char* MakeStringCopy(const char* string)
{
    if(string == NULL){
        return NULL;
    }
    char* res = (char*)malloc(strlen(string)+1);
    strcpy(res, string);
    return res;
}

@implementation WXApiManager
+(instancetype) shareManager
{
    static dispatch_once_t onceToken;
    static WXApiManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[WXApiManager alloc] init];
    });
    return instance;
}
// 微信发送请求到第三方应用时，会回调到该方法
-(void) onReq:(BaseReq *)req
{

}
// 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
-(void) onResp:(BaseResp *)resp
{
    SendAuthResp *temp = (SendAuthResp*)resp;
    int errorCode = temp.errCode;
    switch (errorCode)
    {
        case 0:
        {
            State = 2;
            NSString *message = [NSString stringWithFormat:@"%@",temp.code];
            const char* codeInfo = [message cStringUsingEncoding:NSASCIIStringEncoding];
            Result = MakeStringCopy(codeInfo);
            break;
        }
        case -2:
        {
            State = -2;
            break;
        }
        case -4:
        {
            State = -3;
            break;
        }
        default:
        {
            State = -4;
            break;
        }
    }
}
@end

extern "C"
{
    //微信登录
    void Auth(char* appId, char* uLink)
    {
        State = 1;

        //向微信注册appid:填写自己微信开放平台的appid信息
        NSString *nsAppId = [NSString stringWithFormat:@"%s", appId];
        NSString *nsUniversalLink = [NSString stringWithFormat:@"%s", uLink];
        [WXApi registerApp:nsAppId universalLink:nsUniversalLink];
    
        if([WXApi isWXAppInstalled] == false)
        {
            State = -1;
            return;
        }

        //授权登录
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"wechat_sdk_auth";
        //[WXApi sendReq:req];
        [WXApi sendReq:req completion:^(BOOL success)
        {
            //NSLog(@"唤起微信:%@", success ? @"成功" : @"失败");
        }];
    }
    int GetState()
    {
        return State;
    }
    char* GetResult()
    {
        return MakeStringCopy(Result);
    }
}